/**
 * 系统设置页面
 * 提供博客系统的各种配置选项，包括网站信息、用户管理等
 */

'use client';

import { useState, useEffect } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Switch } from '@/components/ui/switch';
import { Separator } from '@/components/ui/separator';
import { 
  Settings, 
  Globe, 
  User, 
  Mail, 
  Shield, 
  Database,
  Save,
  RefreshCw,
  FileText
} from 'lucide-react';

// 设置数据接口
interface SettingsData {
  site: {
    name: string;
    description: string;
    url: string;
    logo: string;
  };
  user: {
    allowRegistration: boolean;
    requireEmailVerification: boolean;
    defaultRole: string;
  };
  content: {
    allowComments: boolean;
    moderateComments: boolean;
    maxTagsPerPost: number;
  };
  system: {
    maintenanceMode: boolean;
    cacheEnabled: boolean;
    analyticsEnabled: boolean;
  };
}

/**
 * 系统设置页面组件
 * @returns JSX 元素
 */
export default function SettingsPage() {
  const [settings, setSettings] = useState<SettingsData>({
    site: {
      name: '我的博客',
      description: '分享技术见解，记录学习历程，探索无限可能',
      url: 'http://localhost:3000',
      logo: ''
    },
    user: {
      allowRegistration: true,
      requireEmailVerification: false,
      defaultRole: 'USER'
    },
    content: {
      allowComments: true,
      moderateComments: true,
      maxTagsPerPost: 10
    },
    system: {
      maintenanceMode: false,
      cacheEnabled: true,
      analyticsEnabled: false
    }
  });
  const [loading, setLoading] = useState(false);
  const [saving, setSaving] = useState(false);

  useEffect(() => {
    // 这里可以从API加载设置数据
    // 目前使用默认值
  }, []);

  /**
   * 保存设置
   */
  const handleSave = async () => {
    setSaving(true);
    try {
      // 这里可以调用API保存设置
      console.log('保存设置:', settings);
      
      // 模拟保存延迟
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      alert('设置保存成功！');
    } catch (error) {
      console.error('保存设置失败:', error);
      alert('保存设置失败，请重试');
    } finally {
      setSaving(false);
    }
  };

  /**
   * 重置设置
   */
  const handleReset = () => {
    if (confirm('确定要重置所有设置为默认值吗？')) {
      setSettings({
        site: {
          name: '我的博客',
          description: '分享技术见解，记录学习历程，探索无限可能',
          url: 'http://localhost:3000',
          logo: ''
        },
        user: {
          allowRegistration: true,
          requireEmailVerification: false,
          defaultRole: 'USER'
        },
        content: {
          allowComments: true,
          moderateComments: true,
          maxTagsPerPost: 10
        },
        system: {
          maintenanceMode: false,
          cacheEnabled: true,
          analyticsEnabled: false
        }
      });
    }
  };

  return (
    <div className="min-h-screen bg-background">
      <div className="container mx-auto px-4 py-8">
        {/* 页面标题 */}
        <div className="mb-8">
          <h1 className="text-3xl font-bold mb-2">系统设置</h1>
          <p className="text-muted-foreground">配置博客系统的各种选项</p>
        </div>

        <div className="grid gap-6 lg:grid-cols-3">
          {/* 设置表单 */}
          <div className="lg:col-span-2 space-y-6">
            {/* 网站信息设置 */}
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <Globe className="h-5 w-5" />
                  网站信息
                </CardTitle>
                <CardDescription>配置网站的基本信息</CardDescription>
              </CardHeader>
              <CardContent className="space-y-4">
                <div>
                  <Label htmlFor="siteName">网站名称</Label>
                  <Input
                    id="siteName"
                    value={settings.site.name}
                    onChange={(e) => setSettings(prev => ({
                      ...prev,
                      site: { ...prev.site, name: e.target.value }
                    }))}
                    placeholder="输入网站名称"
                  />
                </div>
                <div>
                  <Label htmlFor="siteDescription">网站描述</Label>
                  <Textarea
                    id="siteDescription"
                    value={settings.site.description}
                    onChange={(e) => setSettings(prev => ({
                      ...prev,
                      site: { ...prev.site, description: e.target.value }
                    }))}
                    placeholder="输入网站描述"
                    rows={3}
                  />
                </div>
                <div>
                  <Label htmlFor="siteUrl">网站URL</Label>
                  <Input
                    id="siteUrl"
                    value={settings.site.url}
                    onChange={(e) => setSettings(prev => ({
                      ...prev,
                      site: { ...prev.site, url: e.target.value }
                    }))}
                    placeholder="https://example.com"
                  />
                </div>
                <div>
                  <Label htmlFor="siteLogo">Logo URL</Label>
                  <Input
                    id="siteLogo"
                    value={settings.site.logo}
                    onChange={(e) => setSettings(prev => ({
                      ...prev,
                      site: { ...prev.site, logo: e.target.value }
                    }))}
                    placeholder="https://example.com/logo.png"
                  />
                </div>
              </CardContent>
            </Card>

            {/* 用户管理设置 */}
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <User className="h-5 w-5" />
                  用户管理
                </CardTitle>
                <CardDescription>配置用户注册和权限相关设置</CardDescription>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="flex items-center justify-between">
                  <div className="space-y-0.5">
                    <Label>允许用户注册</Label>
                    <p className="text-sm text-muted-foreground">
                      是否允许新用户注册账号
                    </p>
                  </div>
                  <Switch
                    checked={settings.user.allowRegistration}
                    onCheckedChange={(checked) => setSettings(prev => ({
                      ...prev,
                      user: { ...prev.user, allowRegistration: checked }
                    }))}
                  />
                </div>
                <div className="flex items-center justify-between">
                  <div className="space-y-0.5">
                    <Label>需要邮箱验证</Label>
                    <p className="text-sm text-muted-foreground">
                      注册时是否需要验证邮箱
                    </p>
                  </div>
                  <Switch
                    checked={settings.user.requireEmailVerification}
                    onCheckedChange={(checked) => setSettings(prev => ({
                      ...prev,
                      user: { ...prev.user, requireEmailVerification: checked }
                    }))}
                  />
                </div>
                <div>
                  <Label htmlFor="defaultRole">默认用户角色</Label>
                  <select
                    id="defaultRole"
                    value={settings.user.defaultRole}
                    onChange={(e) => setSettings(prev => ({
                      ...prev,
                      user: { ...prev.user, defaultRole: e.target.value }
                    }))}
                    className="w-full px-3 py-2 border border-input bg-background rounded-md"
                  >
                    <option value="USER">普通用户</option>
                    <option value="ADMIN">管理员</option>
                  </select>
                </div>
              </CardContent>
            </Card>

            {/* 内容管理设置 */}
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <FileText className="h-5 w-5" />
                  内容管理
                </CardTitle>
                <CardDescription>配置文章和评论相关设置</CardDescription>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="flex items-center justify-between">
                  <div className="space-y-0.5">
                    <Label>允许评论</Label>
                    <p className="text-sm text-muted-foreground">
                      是否允许用户对文章进行评论
                    </p>
                  </div>
                  <Switch
                    checked={settings.content.allowComments}
                    onCheckedChange={(checked) => setSettings(prev => ({
                      ...prev,
                      content: { ...prev.content, allowComments: checked }
                    }))}
                  />
                </div>
                <div className="flex items-center justify-between">
                  <div className="space-y-0.5">
                    <Label>评论需要审核</Label>
                    <p className="text-sm text-muted-foreground">
                      评论是否需要管理员审核后才能显示
                    </p>
                  </div>
                  <Switch
                    checked={settings.content.moderateComments}
                    onCheckedChange={(checked) => setSettings(prev => ({
                      ...prev,
                      content: { ...prev.content, moderateComments: checked }
                    }))}
                  />
                </div>
                <div>
                  <Label htmlFor="maxTags">每篇文章最大标签数</Label>
                  <Input
                    id="maxTags"
                    type="number"
                    min="1"
                    max="20"
                    value={settings.content.maxTagsPerPost}
                    onChange={(e) => setSettings(prev => ({
                      ...prev,
                      content: { ...prev.content, maxTagsPerPost: parseInt(e.target.value) || 10 }
                    }))}
                  />
                </div>
              </CardContent>
            </Card>

            {/* 系统设置 */}
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <Settings className="h-5 w-5" />
                  系统设置
                </CardTitle>
                <CardDescription>配置系统运行相关设置</CardDescription>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="flex items-center justify-between">
                  <div className="space-y-0.5">
                    <Label>维护模式</Label>
                    <p className="text-sm text-muted-foreground">
                      开启后网站将显示维护页面
                    </p>
                  </div>
                  <Switch
                    checked={settings.system.maintenanceMode}
                    onCheckedChange={(checked) => setSettings(prev => ({
                      ...prev,
                      system: { ...prev.system, maintenanceMode: checked }
                    }))}
                  />
                </div>
                <div className="flex items-center justify-between">
                  <div className="space-y-0.5">
                    <Label>启用缓存</Label>
                    <p className="text-sm text-muted-foreground">
                      启用页面和数据缓存以提高性能
                    </p>
                  </div>
                  <Switch
                    checked={settings.system.cacheEnabled}
                    onCheckedChange={(checked) => setSettings(prev => ({
                      ...prev,
                      system: { ...prev.system, cacheEnabled: checked }
                    }))}
                  />
                </div>
                <div className="flex items-center justify-between">
                  <div className="space-y-0.5">
                    <Label>启用分析</Label>
                    <p className="text-sm text-muted-foreground">
                      启用访问统计和分析功能
                    </p>
                  </div>
                  <Switch
                    checked={settings.system.analyticsEnabled}
                    onCheckedChange={(checked) => setSettings(prev => ({
                      ...prev,
                      system: { ...prev.system, analyticsEnabled: checked }
                    }))}
                  />
                </div>
              </CardContent>
            </Card>
          </div>

          {/* 操作面板 */}
          <div className="space-y-6">
            <Card>
              <CardHeader>
                <CardTitle>操作</CardTitle>
                <CardDescription>保存或重置设置</CardDescription>
              </CardHeader>
              <CardContent className="space-y-4">
                <Button 
                  onClick={handleSave} 
                  disabled={saving}
                  className="w-full"
                >
                  {saving ? (
                    <>
                      <RefreshCw className="h-4 w-4 mr-2 animate-spin" />
                      保存中...
                    </>
                  ) : (
                    <>
                      <Save className="h-4 w-4 mr-2" />
                      保存设置
                    </>
                  )}
                </Button>
                <Button 
                  variant="outline" 
                  onClick={handleReset}
                  className="w-full"
                >
                  重置为默认值
                </Button>
              </CardContent>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle>系统信息</CardTitle>
                <CardDescription>当前系统状态</CardDescription>
              </CardHeader>
              <CardContent className="space-y-3">
                <div className="flex justify-between text-sm">
                  <span className="text-muted-foreground">Next.js 版本</span>
                  <span>15.5.2</span>
                </div>
                <div className="flex justify-between text-sm">
                  <span className="text-muted-foreground">数据库</span>
                  <span>SQLite</span>
                </div>
                <div className="flex justify-between text-sm">
                  <span className="text-muted-foreground">运行环境</span>
                  <span>开发环境</span>
                </div>
                <Separator />
                <div className="text-xs text-muted-foreground">
                  <p>最后更新: {new Date().toLocaleString('zh-CN')}</p>
                </div>
              </CardContent>
            </Card>
          </div>
        </div>
      </div>
    </div>
  );
}
